<template>
  <div class="chuantu kflexc">

    <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/" :on-change="uploadok"
      :auto-upload="false" :show-file-list="false">
      <img v-if="img" :src="img" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      <div v-if="img" style="position: absolute; right: 5px; top: 5px; border-radius: 2px; padding: 2px 15px; z-index: 999; background: rgba(0, 0, 0, 0.5); color: #fff; line-height: 25px;" @click.stop="shanchu()">删除</div>
    </el-upload>

  </div>
</template>

<script>
  import axios from "axios";
  export default {
    name: 'chuantu',
    props:['imgs'],
    data() {
      return {
        img: ""
      }
    },
    created() {
      if(this.imgs){
        this.img = this.imgs
      }
    },
    methods: {
      shanchu:function(){
        this.img = ""
        this.$emit('getimg', "")
      },
      dataURLtoFile(dataurl, filename) {
        let arr = dataurl.split(","),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {
          type: mime
        });
      },
      //单个图片上传
      uploadok: function(file) {
        var that = this;
        var reader = new FileReader()
        var img = new Image();
        reader.onload = function(e) {
          img.src = e.target.result;
        };
        var canvas = document.createElement('canvas');
        var context = canvas.getContext('2d');
        // base64地址图片加载完毕后
        let p = new Promise((r, j) => {
          img.onload = function() {
            // 图片原始尺寸
            var originWidth = this.width;
            var originHeight = this.height;
            // 最大尺寸限制
            var maxWidth = 1920,
                maxHeight = 10800;
            // 目标尺寸
            var targetWidth = originWidth,
              targetHeight = originHeight;
            // 图片尺寸超过400x400的限制
            if (originWidth > maxWidth || originHeight > maxHeight) {		              if (originWidth / originHeight > maxWidth / maxHeight) {                 // 更宽，按照宽度限定尺寸                  targetWidth = maxWidth;                  targetHeight = Math.round(maxWidth * (originHeight / originWidth));	              } else {                  targetHeight = maxHeight;                 targetWidth = Math.round(maxHeight * (originWidth / originHeight));		              }
            }
            // canvas对图片进行缩放
            canvas.width = targetWidth;
            canvas.height = targetHeight;
            // 清除画布
            context.clearRect(0, 0, targetWidth, targetHeight);
            // 图片压缩
            context.drawImage(img, 0, 0, targetWidth, targetHeight);

            let base64 = canvas.toDataURL("image/png", 1); // 压缩后的base64图片
            let file2 = that.dataURLtoFile(base64, Date.parse(Date()) + ".png");
            r(file2)
          };
        })
        reader.readAsDataURL(file.raw);
        p.then(files => {
          var formData = new FormData();
          formData.append("pic", files);
          axios.post('/api/plan-market/order-page/upload-pic', formData)
            .then(response => {
              if (response.data.msg.code == 0) {
                that.img = response.data.data
                that.$emit('getimg', response.data.data)
              } else {
                that.$message.error(response.data.msg.info);
              }
            })
        })
      }

    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

    .avatar-uploader{
    	border: 1px dashed #d9d9d9;
    	border-radius: 6px;
    	cursor: pointer;
    	position: relative;
    	overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
    	border-color: #409EFF;
    }

    .avatar-uploader-icon {
    	font-size: 28px;
    	color: #8c939d;
    	width: 178px;
    	height: 178px;
    	line-height: 178px;
    	text-align: center;
    }

    /deep/ .el-upload {
    	max-width: 178px;
    	max-height: 178px;
    	display: flex;
      align-items: center;
      justify-content: center;
    }
    /deep/ .el-upload img{ max-width: 178px; max-height: 178px;}
</style>
